package kava.framework.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.rms.RecordStore;

public class Util {

	public static byte[] int2Bytes(int value, int len) {
		byte[] bytes = new byte[len];
		for (int i = len - 1; i >= 0; i--) {
			bytes[i] = (byte) ((value >> (8 * (len - 1 - i))) & 0xff);
		}
		return bytes;
	}

	public static void int2Bytes(int value, int len, byte[] target, int offset) {
		for (int i = len - 1; i >= 0; i--) {
			target[offset + i] = (byte) ((value >> (8 * (len - 1 - i))) & 0xff);
		}
	}

	public static int bytes2Int(byte[] bytes) {
		return bytes2Int(bytes, 0, bytes.length);
	}

	public static int bytes2Int(byte[] bytes, int offset, int len) {
		int value = 0;
		for (int i = len - 1; i >= 0; i--) {
			int b = bytes[offset + i] & 0xff;
			value = (b << (8 * (len - 1 - i))) | value;
		}
		return value;
	}

	public static final boolean testPointInRect(int _x, int _y, int x, int y,
			int width, int height) {
		return _x > x && _x <= x + width && _y > y && _y < y + height;
	}

	public static final void debug(String moduleName, Object s) {
		System.out.println("[" + moduleName + "] " + s);
	}

	/**
	 * Split string into multiple strings
	 * 
	 * @param original
	 *            Original string
	 * @param separator
	 *            Separator string in original string
	 * @return Splitted string array
	 */
	public static final String[] split(String original, String separator) {
		Vector nodes = new Vector();

		// Parse nodes into vector
		int index = original.indexOf(separator);
		while (index >= 0) {
			nodes.addElement(original.substring(0, index));
			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}
		// Get the last node
		nodes.addElement(original);

		// Create splitted string array
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0) {
			for (int loop = 0; loop < nodes.size(); loop++)
				result[loop] = (String) nodes.elementAt(loop);
		}
		return result;
	}

	public static String readUTFFile(String filename, Class c) {
		StringBuffer buffer = new StringBuffer();
		try {
			InputStream is = c.getResourceAsStream(filename);
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			int ch;
			while ((ch = isr.read()) > -1) {
				buffer.append((char) ch);
			}
			// motobug
			try {
				isr.close();
			} catch (Exception e) {

			}
			// is.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return buffer.toString();
	}

	public static int parseInt(String s) {
		if (s.startsWith("0x") || s.startsWith("0x")) {
			return Integer.parseInt(s.substring(2), 16);
		} else {
			return Integer.parseInt(s);
		}
	}

	// the first Element is the type,the next is the byte[]
	public static Vector getViaHttpConnection(String url, String x_online_host,
			NetLoadListener listener) {
		Util.debug("Util.getViaHttpConnection", "url = " + url);
		HttpConnection c = null;
		InputStream is = null;
		int rc;
		byte[] data = null;
		String type = null;
		try {
			c = (HttpConnection) Connector.open(url);
			if (c == null) {
				return null;
			}
			c.setRequestMethod(HttpConnection.GET);
			if (x_online_host != null) {
				c.setRequestProperty("X-Online-Host", x_online_host);
			}

			rc = c.getResponseCode();
			if (rc != HttpConnection.HTTP_OK) {
				return null;
			}

			is = c.openInputStream();
			if (is == null) {
				return null;
			}
			type = c.getType();
			Util.debug("Util.getViaHttpConnection", "mime = " + type);
			int len = (int) c.getLength();
			if (listener != null) {
				listener.notifyHeadInfo(type, len);
			}
			if (len > 0) {
				int actual = 0;
				int bytesread = 0;
				data = new byte[len];
				while ((bytesread != len) && (actual != -1)) {
					int toRead = Math.min(1024, len - bytesread);
					actual = is.read(data, bytesread, toRead);
					bytesread += actual;

					if (listener != null && actual > 0) {
						listener.handleStepData(data, bytesread, actual);
					}
				}
			} else {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int ch = 0;
				while ((ch = is.read()) != -1) {
					baos.write(ch);
				}
				baos.close();
				data = baos.toByteArray();
				if (listener != null) {
					listener.handleStepData(data, 0, data.length);
				}

			}
		} catch (Throwable e) {
			data = null;
			e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
				if (c != null)
					c.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (data != null) {
			Vector v = new Vector();
			v.addElement(type);
			v.addElement(data);
			Util.debug("Util.getViaHttpConnection", url + "   treated ok");
			return v;
		}
		return null;
	}

	public final static String byteArrayToHexString(byte in[]) {
		byte ch = 0x00;
		int i = 0;
		if (in == null || in.length <= 0)
			return null;
		String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"A", "B", "C", "D", "E", "F" };
		StringBuffer out = new StringBuffer(in.length * 2);
		while (i < in.length) {
			ch = (byte) (in[i] & 0xF0); // Strip off high nibble
			ch = (byte) (ch >>> 4);
			// shift the bits down
			ch = (byte) (ch & 0x0F);
			// must do this is high order bit is on!
			out.append(pseudo[(int) ch]); // convert the nibble to a String
			// Character
			ch = (byte) (in[i] & 0x0F); // Strip off low nibble
			out.append(pseudo[(int) ch]); // convert the nibble to a String
			// Character
			i++;

		}
		String rslt = new String(out);
		return rslt;

	}

	public static final int[] getNumberArray(int value) {
		Vector v = new Vector();
		while (value / 10 > 0) {
			int a = value % 10;
			v.addElement(new Integer(a));
			value = value / 10;
		}
		v.addElement(new Integer(value));
		int size = v.size();
		int[] result = new int[size];
		for (int i = 0; i < size; i++) {
			Integer iv = (Integer) v.elementAt(size - 1 - i);
			result[i] = iv.intValue();
		}
		return result;
	}

	public static final int getCelling(int big, int small) {
		return big % small == 0 ? big / small : big / small + 1;
	}

	public static final int getFloor(int big, int small) {
		return big / small;
	}

	public static String strReplace(String _text, String _searchStr,
			String _replacementStr) {
		// String buffer to store str
		StringBuffer sb = new StringBuffer();

		// Search for search
		int searchStringPos = _text.indexOf(_searchStr);
		int startPos = 0;
		int searchStringLength = _searchStr.length();

		// Iterate to add string
		while (searchStringPos != -1) {
			sb.append(_text.substring(startPos, searchStringPos)).append(
					_replacementStr);
			startPos = searchStringPos + searchStringLength;
			searchStringPos = _text.indexOf(_searchStr, startPos);
		}

		// Create string
		sb.append(_text.substring(startPos, _text.length()));

		return sb.toString();
	}

	public static boolean isRmsExist(String dbName) {
		String[] dbs = RecordStore.listRecordStores();
		if (dbs != null && dbs.length > 0) {
			for (int i = 0; i < dbs.length; i++) {
				String string = dbs[i];
				if (string.equals(dbName)) {
					return true;
				}
			}
		}
		return false;
	}

}
